((lambda ()

  (var fs   (require "fs"))
  (var glob (require "glob"))
  (var path (require "path"))

  (return (|| (load-library) (scan-library)))

  (function load-library ()
    (console.log "loading library from" ./options/file)
    (try
      (var data (fs.read-file-sync ./options/file "utf8"))
      (catch err
        (console.error "error reading" ./options/file)
        (return (write-library (scan-library)))))
    (try
      (return (JSON.parse data))
      (catch err
        (console.error "error parsing" ./options/file)
        (return (write-library (scan-library))))))

  (function scan-library ()
    (console.log "scanning library at" ./options/dir)
    (var files (glob.sync
      (path.join ./options/dir "**" "*")
      (object "nodir" true)))
    (return (files.reduce (lambda (library file)
      (= (get library (path.relative ./options/dir file)) (object))
      (return library)) (object))))

  (function write-library (data)
    (console.log "writing library to" ./options/file)
    (try
      (fs.write-file-sync ./options/file (JSON.stringify data))
      (catch err
        (console.error "error writing" ./options/file))
      (finally
        (return data))))

))
